package com.your.netty.sample.biz;

import io.netty.channel.ChannelHandlerContext;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;

import com.your.netty.sample.core.Application;
import com.your.netty.sample.core.RequestData;
import com.your.netty.sample.server.ChannelUtil;
import com.your.netty.sample.server.ResponseMessage;

public class OperIntegralExecutor implements Runnable {
	private static final Logger logger = Logger.getLogger(OperIntegralExecutor.class);

	private RequestData dataRequestData;
	private ChannelHandlerContext channelHandlerContext;

	public OperIntegralExecutor(ChannelHandlerContext ctx, RequestData dataRequestData) {
		super();
		this.dataRequestData = dataRequestData;
		this.channelHandlerContext = ctx;
	}

	@Override
	public void run() {
		ResponseMessage responseMessage = null;
		try {
			// 调用业务服务接口
			Object service = Application.ctx.getBean(this.dataRequestData.getServiceName());
			BizService bizService = (BizService) service;
			responseMessage = bizService.execute(this.dataRequestData);
		} catch (NoSuchBeanDefinitionException e) {
			responseMessage = new ResponseMessage(true, "服务[" + this.dataRequestData.getServiceName() + "] 不存在");
		} catch (Throwable e) {
			logger.warn("接口处理错误", e);
			responseMessage = new ResponseMessage(false, e.getMessage());
		} finally {
			ChannelUtil.writeResponseMessage(responseMessage, channelHandlerContext, null);
		}
	}

	public RequestData getDataRequestData() {
		return dataRequestData;
	}

	public void setDataRequestData(RequestData dataRequestData) {
		this.dataRequestData = dataRequestData;
	}

}
